package com.dhy.domain;

import com.dhy.util.RabbitmqUtil;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

import static com.dhy.constants.RabbitmqConstants.DEFAULT_CHANGE;

/**
 * 发送请求到服务端,然后接受到服务器发回的响应数据
 */
@Slf4j
public class Client implements Runnable{
    final BlockingQueue<String> response = new ArrayBlockingQueue<>(1);
    RabbitmqUtil rabbitmqUtil = null;
    @Override
    public void run() {
        try {
            rabbitmqUtil = new RabbitmqUtil("application.yml");
            Channel client = rabbitmqUtil.createChannel();
            String rpcQueue = client.queueDeclare().getQueue();
            log.info("rpc队列名为: {}",rpcQueue);
            String uid = UUID.randomUUID().toString();
            AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                    //发送的消息关联的唯一ID
                    .correlationId(uid)
                    //消息发送到哪个队列
                    .replyTo(rpcQueue).
                    build();
            //使用默认交换机,路由key为rpc,路由失败会调用消息回退接口
            client.basicPublish("","rpc_queue",true,props,"rpc".getBytes(StandardCharsets.UTF_8));
            //监听rpc队列中回复的消息--返回的是当前消费者的标签
            String ctag = client.basicConsume(rpcQueue, true, (consumerTag, delivery) -> {
                if (delivery.getProperties().getCorrelationId().equals(uid)) {
                    response.offer(new String(delivery.getBody()));
                }
            }, consumerTag -> {
            });

            //阻塞取,直到队列中存在消息
            String res = response.take();
            //取消当前消费者---临时队列会被删除
            client.basicCancel(ctag);
            log.info("拿到rpc返回的结果: {}",res);
        } catch (IOException | TimeoutException | InterruptedException e) {
            log.error("出现异常: ",e);
        }
    }

    public Connection getConn(){
        if(rabbitmqUtil!=null){
            return  rabbitmqUtil.getConnection();
        }
        return null;
    }
}
